//
//  TouchableView.swift
//  SitPosition
//
//  Created by apple on 2019/2/8.
//  Copyright © 2019 apple. All rights reserved.
//

import Foundation
import UIKit


/**
 * 封装单击、双击手势的UIView
 */
class TouchableView : UIView {
    
    public var onTap: () -> Void = { }
    public var onDoubleTap: () -> Void = { }
    
    private var hasInited: Bool = false
    
    override func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
        if !hasInited {
            hasInited = true
            
            let singleTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(_handleSingleTap(_:)))
            singleTap.numberOfTapsRequired = 1
            singleTap.numberOfTouchesRequired = 1
            addGestureRecognizer(singleTap)
            
            let doubleTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(_handleDoubleTap(_:)))
            doubleTap.numberOfTouchesRequired = 1
            doubleTap.numberOfTapsRequired = 2
            addGestureRecognizer(doubleTap)
            
            singleTap.require(toFail: doubleTap)
        }
    }
    
    @objc func _handleSingleTap(_ gesture: UIGestureRecognizer) {
        onTap()
    }
    
    @objc func _handleDoubleTap(_ gesture: UIGestureRecognizer) {
        onDoubleTap()
    }
}
